package com.hdl.client.handler;

import com.hdl.RpcRequest;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.concurrent.Callable;

/**
 * @author Administrator
 */
public class NettyClientHandler extends ChannelInboundHandlerAdapter implements Callable {
    private ChannelHandlerContext context;
    private String result;
    private RpcRequest para;
    private Long responseTime = 0L;
    private String connectString;

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        context = ctx;
    }

    /*** 收到服务端数据，唤醒等待线程 */
    @Override
    public synchronized void channelRead(ChannelHandlerContext ctx, Object msg) {
        result = msg.toString();
        notify();
    }

    /*** 写出数据，开始等待唤醒 */
    @Override
    public synchronized Object call() throws InterruptedException {
        long startTime = System.currentTimeMillis();
        context.writeAndFlush(para);
        wait();
        long endTime= System.currentTimeMillis();
        // 设置响应时间
        this.setResponseTime(endTime - startTime);
        System.out.println("==========>>>>>>>服务器"+ connectString +"响应时间："  + (endTime - startTime) + "ms");
        return result;
    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("Netty客户端异常" + cause);
        // 客户端设置5s为超时时间，超时就会走异常处理，设置响应事假为0
        this.setResponseTime(0L);
    }

    public void setPara(RpcRequest para) {
        this.para = para;
    }


    public Long getResponseTime() {
        return responseTime;
    }

    public void setResponseTime(Long responseTime) {
        this.responseTime = responseTime;
    }


    public String getConnectString() {
        return connectString;
    }

    public void setConnectString(String connectString) {
        this.connectString = connectString;
    }
}